//
//  MySearchViewController.m
//  HuiKaoClient
//
//  Created by 龚 杰 on 13-3-7.
//  Copyright (c) 2013年 龚 杰. All rights reserved.
//

#import "MySearchViewController.h"
#import "MainTabBarController.h"
#import "AppDelegate.h"
#import "MyOrderCell.h"
#import "MyTrainingCell.h"

@interface MySearchViewController ()

@end

@implementation MySearchViewController
@synthesize mySearchType = m_mySearchType;

- (id)init
{
    if (self = [super init]) {
        m_SearchDataArray = [[NSMutableArray alloc] init];
    }
    return self;
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if ([m_titleBttBarItem superview] == nil) {
        [self.navigationController.navigationBar addSubview:m_titleBttBarItem];
    }
    if ([m_BackBttBarItem superview] == nil) {
        [self.navigationController.navigationBar addSubview:m_BackBttBarItem];
    }
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:) name:UIKeyboardDidShowNotification object:nil];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    if ([m_BackBttBarItem superview]) {
        [m_BackBttBarItem removeFromSuperview];
    }
    if ([m_titleBttBarItem superview]) {
        [m_titleBttBarItem removeFromSuperview];
    }
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
	[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

- (void)keyboardWillShow:(NSNotification *)note {
    // if clause is just an additional precaution, you could also dismiss it

    [self addButtonToKeyboard];
}

- (void)keyboardDidShow:(NSNotification *)note {
    // if clause is just an additional precaution, you could also dismiss it
    [self addButtonToKeyboard];
}
- (void)addButtonToKeyboard
{
    UIButton *doneButton = [UIButton buttonWithType:UIButtonTypeCustom];
    doneButton.frame = CGRectMake(0, 163, 106, 53);
    doneButton.adjustsImageWhenHighlighted = NO;
    [doneButton setImage:[UIImage imageNamed:@"doneup.png"] forState:UIControlStateNormal];
    [doneButton setImage:[UIImage imageNamed:@"donedown.png"] forState:UIControlStateHighlighted];
    [doneButton addTarget:self action:@selector(doneButton:) forControlEvents:UIControlEventTouchUpInside];
    // locate keyboard view
    UIWindow* tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1];
    UIView* keyboard;
    for(int i=0; i<[tempWindow.subviews count]; i++) {
        keyboard = [tempWindow.subviews objectAtIndex:i];
        // keyboard found, add the button
        if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.2) {
            if([[keyboard description] hasPrefix:@"<UIPeripheralHost"] == YES)
                [keyboard addSubview:doneButton];
        } else {
            if([[keyboard description] hasPrefix:@"<UIKeyboard"] == YES)
                [keyboard addSubview:doneButton];
        }
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    if (m_mySearchType == MST_OR) {
        m_titleBttBarItem = [[MainTabBarController setTitle:@"搜索订单"] retain];
    }else{
        m_titleBttBarItem = [[MainTabBarController setTitle:@"搜索培训班"] retain];
    }

    m_BackBttBarItem = [UIButton buttonWithType:UIButtonTypeCustom];
    m_BackBttBarItem.frame = CGRectMake(5, 7, 50, 30);
    [m_BackBttBarItem setBackgroundImage:[UIImage imageNamed:@"button_back.png"] forState:UIControlStateNormal];
    [m_BackBttBarItem setTitle:@"返回" forState:UIControlStateNormal];
    [m_BackBttBarItem setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    m_BackBttBarItem.titleLabel.font = [UIFont systemFontOfSize:13.0f];
    [m_BackBttBarItem addTarget:self action:@selector(navBackBtt) forControlEvents:UIControlEventTouchUpInside];
    [m_BackBttBarItem retain];
    
    m_SearchView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
    UISearchBar* tSearchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
    tSearchBar.placeholder = @"请输入手机号或订单号搜索";
    tSearchBar.tag =0x10;
    tSearchBar.delegate = self;
    tSearchBar.keyboardType = UIKeyboardTypeNumberPad;
    tSearchBar.tintColor =[UIColor lightGrayColor];
    [m_SearchView addSubview:tSearchBar];
    [tSearchBar release];
    [self.view addSubview:m_SearchView];
    
    if (m_mySearchType == MST_OR) {
         m_MSTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 44, 320, self.view.frame.size.height-49-44) style:UITableViewStyleGrouped];
    }else{
         m_MSTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 44, 320, self.view.frame.size.height-49-44) style:UITableViewStylePlain];
    }
    m_MSTableView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    m_MSTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    UIView* iview = [[UIView alloc] initWithFrame:m_MSTableView.frame];
    [iview setBackgroundColor:[UIColor colorWithRed:242/250.f green:242/255.0f blue:242/255.0f alpha:1.0]];
    m_MSTableView.backgroundView = iview;
    [iview release];
    [m_MSTableView setDataSource:self];
    [m_MSTableView setDelegate:self];
    [self.view addSubview:m_MSTableView];
}
- (void)navBackBtt
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)doneButton:(id)iButton
{
    UISearchBar* iSearchBar = (UISearchBar*)[m_SearchView viewWithTag:0x10];
    NSString* str =  iSearchBar.text;
    NSLog(@"%@",str);
    [iSearchBar setShowsCancelButton:NO animated:YES];
    [iSearchBar resignFirstResponder];
    if (str.length>0) {
        HttpInterfaceManager* iHttpInterface = [HttpInterfaceManager sharedManager];
        iHttpInterface.delegate = self;
        if (m_mySearchType == MST_OR) {
            [iHttpInterface OrderSearchRequestGet:str];
        }else{
            [iHttpInterface ClassesSearchRequestGet:str];
        }
        [self addHudLoad];
    }else{
        AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
        [tAppDel showWithCustomView:@"提示" detailText:@"请输入手机号或订单号" isCue:YES delayTime:1.0f];

    }

}
#pragma mark UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [m_SearchDataArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
     if (m_mySearchType == MST_OR) {
         static NSString* tCellstr = @"MyOCell";
         MyOrderCell* tCell = [tableView dequeueReusableCellWithIdentifier:tCellstr];
         if (tCell == nil) {
             tCell = [[[MyOrderCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:tCellstr] autorelease];
             tCell.accessoryType = UITableViewCellAccessoryNone;
             tCell.selectionStyle = UITableViewCellSelectionStyleNone;
         }
         NSInteger row = indexPath.row;
         NSDictionary* dic = [m_SearchDataArray objectAtIndex:row];
         NSString* price = [dic objectForKey:@"price"];
         NSString* status = [dic objectForKey:@"status"];
         tCell.priceLabel.text = [NSString stringWithFormat:@"订单总价：¥%@",price];//@"订单总价：¥200";
         tCell.stateLabel.text = [NSString stringWithFormat:@"状态：%@",status];//@"状态：等待付款";
         
         NSMutableArray* iarray = [NSMutableArray arrayWithArray:[dic objectForKey:@"product_list"]];
         [tCell setData:iarray pay:[dic objectForKey:@"pay_flag"]];
         tCell.numLabel.text = [NSString stringWithFormat:@"共%d件商品",[iarray count]];
         iarray = nil;
         return tCell;
     }else{
         static NSString* tCellstr = @"MyTraining";
         MyTrainingCell* tCell = [tableView dequeueReusableCellWithIdentifier:tCellstr];
         if (tCell == nil) {
             tCell = [[[MyTrainingCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:tCellstr] autorelease];
             tCell.accessoryType = UITableViewCellAccessoryNone;
             tCell.selectionStyle = UITableViewCellSelectionStyleNone;
         }
         NSInteger row = indexPath.row;
         NSDictionary* dis = (NSDictionary*)[m_SearchDataArray objectAtIndex:row];
         tCell.trname.text = [dis objectForKey:@"name"];//@"2013年国考21天面试起飞套餐";
         NSString* time = [dis objectForKey:@"time"];
         tCell.trtime.text =  [NSString stringWithFormat:@"学时：%@学时",time];//@"学时：20学时";
         NSString* teacher = [dis objectForKey:@"teacher"];
         tCell.trteacher.text = [NSString stringWithFormat:@"教师：%@",teacher];//@"教师：李强";
         NSString* address = [dis objectForKey:@"address"];
         tCell.traddress.text = [NSString stringWithFormat:@"地点：%@",address];//@"地点：长江后街98号";
         NSString* stime = [dis objectForKey:@"start"];
         tCell.trstime.text = [NSString stringWithFormat:@"开课时间：%@",stime];//@"开课时间：2012-12-12";
         NSString* money = [dis objectForKey:@"price"];
         tCell.trmoney.text = [NSString stringWithFormat:@"¥：%@",money];//@"¥：960";
         
         [tCell.trpayment setBackgroundImage:[UIImage imageNamed:@"button_yellow_tiny.png"] forState:UIControlStateNormal];
         [tCell.trpayment setTitle:@"去付款" forState:UIControlStateNormal];
         [tCell.trpayment setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
         tCell.trpayment.titleLabel.font = [UIFont systemFontOfSize:12.0f];
        return tCell;
     }

    return nil;
}


#pragma mark UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (m_mySearchType == MST_OR) {
           return 150;
    }else{
           return 140;
    }
    return 0;
}
#pragma mark-
#pragma mark UISearchBarDelegate
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    [searchBar setShowsCancelButton:YES animated:YES];
    //取消按钮文字 - add by Scott
    for (UIView *searchbuttons in searchBar.subviews)
    {
        if ([searchbuttons isKindOfClass:[UIButton class]])
        {
            UIButton *cancelButton = (UIButton*)searchbuttons;
            //[cancelButton setBackgroundImage:[UIImage imageNamed:@"search_bg.png"] forState:UIControlStateNormal];
            [cancelButton setTitle:@"取消" forState:UIControlStateNormal];//文字
            break;
        }
    }
    return YES;
}
- (void)searchBarCancelButtonClicked:(UISearchBar *) searchBar
{
    [searchBar setShowsCancelButton:NO animated:YES];
    [searchBar resignFirstResponder];
    
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];
}
#pragma mark HttpInterfaceManageDelegate
-(void)RequestResultsOrderSearch:(NSDictionary*)dic
{
    [self hudWasHidden:nil];
    if (dic != nil) {
        [m_SearchDataArray removeAllObjects];
        NSArray* iArray = [dic objectForKey:@"list"];
        for (NSDictionary* dic in iArray) {
            [m_SearchDataArray addObject:dic];
        }
        [m_MSTableView reloadData];
    }
}
-(void)RequestResultsClassesSearch:(NSDictionary*)dic
{
    [self hudWasHidden:nil];
    if (dic != nil) {
        [m_SearchDataArray removeAllObjects];
        NSArray* iArray = [dic objectForKey:@"list"];
        for (NSDictionary* dic in iArray) {
            [m_SearchDataArray addObject:dic];
        }
        [m_MSTableView reloadData];
    }
}
-(void)RequestResultsErrer:(NSDictionary*)dic
{
    [self hudWasHidden:nil];
    AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
    [tAppDel showWithCustomView:@"提示" detailText:[dic objectForKey:@"error_msg"] isCue:YES delayTime:2.0f];

}
#pragma mark MBProgressHUDDelegate
- (void)hudWasHidden:(MBProgressHUD *)hud{
    m_MBHUD.delegate = nil;
	[m_MBHUD removeFromSuperview];
	[m_MBHUD release];
	m_MBHUD=nil;
}

-(void) addHudLoad{
	if (m_MBHUD == nil) {
		m_MBHUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
		// Add HUD to screen
        AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
		[tAppDel.window addSubview:m_MBHUD];
		// Regisete for HUD callbacks so we can remove it from the window at the right time
		m_MBHUD.delegate = self;
		m_MBHUD.labelText = @"请求数据中...";
		[m_MBHUD show:YES];
	}
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)dealloc
{
    [m_SearchView release];
    [m_BackBttBarItem release];
    [m_titleBttBarItem release];
    [m_SearchDataArray release];
    [m_MSTableView release];
    m_MBHUD = nil;

    [super dealloc];
}
@end
